package com.tramp.controller;

import com.tramp.basic.entity.Menu;
import com.tramp.basic.service.MenuService;
import com.tramp.basic.service.RoleMenuService;
import com.tramp.frame.server.base.BaseController;
import com.tramp.frame.server.base.ResultData;
import com.tramp.frame.server.exception.GenericException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;

/**
 * Created by chen on 2017/11/4.
 */
@Controller
@RequestMapping("/menu/")
public class MenuController extends BaseController {

    @Autowired
    private MenuService menuService;
    @Autowired
    private RoleMenuService roleMenuService;
    /**
     * 列表页
     *
     * @return
     */
    @RequestMapping(value = "list")
    public String list() {

        return "menu/list";
    }

    /**
     * 添加页
     *
     * @return
     */
    @RequestMapping(value = "add")
    public String add() {

        return "menu/add";
    }

    /**
     * 菜单tree页
     *
     * @return
     */
    @RequestMapping(value = "tree")
    public String tree() {

        return "menu/tree";
    }

    /**
     * icon页
     *
     * @return
     */
    @RequestMapping(value = "icon")
    public String icon() {

        return "menu/icon";
    }

    /**
     * 列表数据
     *
     * @return
     */
    @RequestMapping("/query")
    @ResponseBody
    public ResultData query() {
        List<Menu> adminList = menuService.listByEntity(new Menu());
        return success(adminList);
    }

    /**
     * 保存
     *
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public ResultData save(@RequestBody Menu menu) {
        if (StringUtils.isNotBlank(menu.getId())) {
            menuService.update(menu);
        } else {
            if (StringUtils.isBlank(menu.getParentId())) {
                menu.setParentId("0");
                menu.setUrl("#");
            }
            menu.setCreateTime(new Date());
            menuService.insert(menu);
        }

        return success(menu);
    }

    /**
     * 根据id查询详情
     *
     * @param id
     * @return
     */
    @RequestMapping("info")
    @ResponseBody
    public ResultData info(String id) {
        Menu menu = menuService.get(id);
        return success(menu);
    }

    /**
     * 删除
     *
     * @return
     */
    @RequestMapping("/remove")
    @ResponseBody
    public ResultData remove(String id) {
        List<Menu> menuList = menuService.getMenusByParent(id);
        if (menuList.size() > 0) {
            throw new GenericException("请先删除子菜单");
        }
        menuService.delete(id);
        roleMenuService.deleteByMenuId(id);
        return success(null);
    }
}
